﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MySqlStudent.UI.Application;
using MySqlStudent.UI.Models;
using MySqlStudent.UI.Models.StudentViewModel;
using MySqlStudent.UI.Repo;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace MySqlStudent.UI.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly IRepository<Student, int> _studentRepository;
        private readonly IStudentService _studentService;

        public HomeController(
            ILogger<HomeController> logger,
            IWebHostEnvironment webHostEnvironment,
            IRepository<Student, int> studentRepository,
            IStudentService studentService)
        {
            _logger = logger;
            _webHostEnvironment = webHostEnvironment;
            _studentRepository = studentRepository;
            _studentService = studentService;
        }

        public async Task<IActionResult> Index(GetStudentInput input)
        {
            var dtos = await _studentService.GetPaginatedResult(input);
            dtos.Data = dtos.Data.ToList();

            return View(dtos);
        }

        public async Task<IActionResult> Detail(int id)
        {
            _logger.LogTrace("学生信息Trace(跟踪)Log");
            _logger.LogDebug("学生信息Debug(调试)Log");
            _logger.LogInformation("学生信息 信息(Information)Log");
            _logger.LogWarning("学生信息 警告(Warning)Log");
            _logger.LogError("学生信息 错误(Error)Log");
            _logger.LogCritical("学生信息 严重 (Critical) Log");

            // 查询所有学生信息
            var student = await _studentRepository.FirstOrDefaultAsync(x => x.Id == id);
            if (student == null)
            {
                ViewBag.ErrorMessage = $"学生Id={id}的信息不存在，请重试,";
                Response.StatusCode = 404;
                return View("StudentNotFound", id);
            }

            return View(student);
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Create(StudentCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if (model.Phones != null && model.Phones.Count > 0)
                {
                    foreach (var phone in model.Phones)
                    {
                        string uploadFolder = Path.Combine(_webHostEnvironment.WebRootPath,
                            "img", "avatar");
                        uniqueFileName = Guid.NewGuid().ToString() + "_" + phone.FileName;
                        string filePath = Path.Combine(uploadFolder, uniqueFileName);
                        phone.CopyTo(new FileStream(filePath, FileMode.Create));
                    }
                }

                Student student = new Student
                {
                    Name = model.Name,
                    Email = model.Email,
                    Marjor = model.Marjor,
                    EnrollmentDate = model.EnrollmentDate,
                    PhonePath = uniqueFileName,
                };

                await _studentRepository.InsertAsync(student);
                return RedirectToAction("detail", new { id = student.Id });
            }

            return View();
        }

        public async Task<IActionResult> Edit(int id)
        {
            var student = await _studentRepository.FirstOrDefaultAsync(x => x.Id == id);
            if (student == null)
            {
                ViewBag.ErrorMessage = $"学生Id={id}的信息不存在，请重试";
                return View("NotFound");
            }

            var editModel = new StudentEditViewModel
            {
                Id = student.Id,
                Name = student.Name,
                Email = student.Email,
                Marjor = student.Marjor,
                ExistingPhotoPath = student.PhonePath,
                EnrollmentDate = student.EnrollmentDate
            };

            return View(editModel);
        }

        [HttpPost]
        public async Task<IActionResult> Edit(StudentEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                var student = await _studentRepository.FirstOrDefaultAsync(x => x.Id == model.Id);

                student.Name = model.Name;
                student.Email = model.Email;
                student.Marjor = model.Marjor;
                student.EnrollmentDate = model.EnrollmentDate;

                // 如果上传了新的图片，可以上伤心城市新图片它会被模型对象上的Photo属性接收
                // 如果用户没有上传图片，那么我们会保留现有的图片信息
                // 因为兼容了多图上传，所有 != null 判断修改判断Photos总数是否大于0
                if (model.Phones != null && model.Phones.Count > 0)
                {
                    // 如果上传的新的图片，则必须显示新的图片信息
                    // 因此我们会检查当前学生信息中是否有图片，有的话，就会删除它
                    if (model.ExistingPhotoPath != null)
                    {
                        string filePath = Path.Combine(_webHostEnvironment.WebRootPath,
                            "img", "avatar", model.ExistingPhotoPath);
                        if (System.IO.File.Exists(filePath))
                        {
                            System.IO.File.Delete(filePath);
                        }
                    }

                    student.PhonePath = ProcessUploadedFile(model);
                }

                Student updatedStudent = await _studentRepository.UpdateAsync(student);
                return RedirectToAction("index");
            }

            return View(model);
        }

        public string ProcessUploadedFile(StudentCreateViewModel model)
        {
            string uniqueFileName = null;
            if (model.Phones.Count > 0)
            {
                foreach (var phone in model.Phones)
                {
                    string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath,
                        "img", "avatar");

                    uniqueFileName = Guid.NewGuid().ToString() + "_" + phone.FileName;
                    string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        // 复制图片到 /wwwroot/img/avatar 文件夹
                        phone.CopyTo(fileStream);
                    }
                }
            }

            return uniqueFileName;
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            var student = await _studentRepository.FirstOrDefaultAsync(x => x.Id == id);
            if (student == null)
            {
                ViewBag.ErrorMessage = $"学生Id={id}的信息不存在";
                return View("NotFound");
            }

            await _studentRepository.DeleteAsync(s => s.Id == id);
            return RedirectToAction("Index");
        }
    }
}